<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 *
 *
 * @icon fa fa-circle-o
 */
class Approach extends Backend
{

    /**
     * Approach模型对象
     * @var \app\admin\model\Approach
     */
    protected $model = null;
    protected $chargedep_data = null;
    protected $tmpFields = [];
    protected $tmpFieldNames = [];
    protected $fieldNames = [];
    public function _initialize()
    {
        parent::_initialize();
        $this->chargedep_model = new \app\admin\model\Chargedep;

        $this->model = new \app\admin\model\Approach;
        $this->chargedep_data = $this->auth->getChargedep();
        $this->assign('isSuperAdmin',$this->auth->isSuperAdmin());
        $this->assignconfig('isSuperAdmin',$this->auth->isSuperAdmin());
        $this -> assign('leaders',getSelectList('leader'));
        $this -> assign('chargeDeps',getSelectList('chargedep'));
        $this -> Fields = [
            'name',
            'inspect_time' ,
            'inspect_address' ,
            'chargedep_ids' ,
            // 'chargedep_names',
            'leader_ids' ,
            // 'leader_names' ,
            'accompany_ids' ,
            // 'accompany_name' ,
            'inspect_memo',
            // 'project_time',
            'project_status',
            // 'project_status_name'
        ];
        $this -> tmpFields = [
            'tmp_name',
            'tmp_inspect_time' ,
            'tmp_inspect_address' ,
            'tmp_chargedep_ids' ,
            'tmp_chargedep_names',
            'tmp_leader_ids' ,
            'tmp_leader_names' ,
            'tmp_accompany_name' ,
            'tmp_inspect_memo',
            'tmp_project_status'
        ];

        $this -> tmpFieldNames = [
            'tmp_name' => __('Name'),
            'tmp_inspect_time' => __('Inspect_time'),
            'tmp_inspect_address' => __('Inspect_address'),
            'tmp_chargedep_ids' => __('Chargedep_ids'),
            'tmp_chargedep_names' => __('Chargedep_ids'),
            'tmp_leader_ids' =>__('Leader_ids'),
            'tmp_leader_names' => __('Leader_ids'),
            'tmp_accompany_name' => __('Accompany_name'),
            'tmp_inspect_memo' =>__('Inspect_memo'),
            'tmp_project_status' =>__('Project_status')
        ];

        $this -> fieldNames = [
            'name' => __('Name'),
            'inspect_time' => __('Inspect_time'),
            'inspect_address' => __('Inspect_address'),
            'chargedep_ids' => __('Chargedep_ids'),
            'chargedep_names' => __('Chargedep_ids'),
            'leader_ids' =>__('Leader_ids'),
            'leader_names' => __('Leader_ids'),
            'accompany_ids' => __('Accompany_ids'),
            'accompany_name' => __('Accompany_name'),
            'inspect_memo' =>__('Inspect_memo'),
            'project_status' =>__('Project_status'),

        ];
        // pr($this -> fieldNames);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);


        // $this->whereExtend['investment_total|tmp_investment_total'] = ['>=', 1];
        // $import_activity = (new Activity)->where(['is_important'=>1])->column('id');
        // $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($project_source_ids,import_activity)")];
        // $this->whereExtend['']
        // $this->whereExtend['is_important'] = 0;
        $groupIds = $this->auth->getGroupIds();

        if(!$this->auth->isSuperAdmin())
        {
            $chargedep_data = $this->auth->getChargedep();
            if($chargedep_data){
                $chargedep_id = $chargedep_data->chargedep_id;
                $this->whereExtend[] = ['exp',Db::raw("FIND_IN_SET($chargedep_id,chargedep_ids)")];
                $this->assignconfig('chargedep_id',$chargedep_id);
            }
            else
                $this->whereExtend[] = ['exp','1<0'];
        }
        // $this->sortExtend = 'inspect_time desc';

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with($this->relationtTable)
                ->where($where)
                ->where($this->whereExtend)
                ->order($sort, $order)
                ->group('name') //分组
                ->count();

            $tmpSql = Db::name('approach')
                -> order('inspect_time desc')
                ->where($where)
                ->where($this->whereExtend)
                ->limit(999999) // 不加limit不生效
                -> buildSql();
            $tmp = \db() -> table($tmpSql . " a")
                ->where($where)
                ->where($this->whereExtend)
                ->limit($offset, $limit)
                ->order($this->sortExtend)
                ->order($sort, $order)
                ->group('a.name')
                ->column('id');

            $list = $this->model
                ->with($this->relationtTable)
                ->whereIn('id',$tmp)
                ->order('id','desc')
                ->select();

            // $list = $this->model
            //     ->with($this->relationtTable)
            //     ->where($where)
            //     ->where($this->whereExtend)
            //     ->order($this->sortExtend)
            //     ->order($sort, $order)
            //     ->limit($offset, $limit)
            //     ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();

    }
    public function add(){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if($this->auth->isSuperAdmin())
                    $pre = '';
                else
                    $pre = 'tmp_';

                $insertData = [];
                if(!$this -> auth -> isSuperAdmin()){
                    foreach ($params as $k => &$v) {
                        if($k == 'name') {
                            $insertData['name'] = $v;
                        }

                        $insertData['tmp_'.$k] =$v;
                        $insertData['tmp_'.$k.'_status'] =STATUS_SUBMIT;
                        unset($params[$k]);
                    }
                    $insertData['chargedep_ids'] = $this->chargedep_data->chargedep_id;
                    $insertData['chargedep_names'] = $this->chargedep_data->nickname;
                    $insertData['status'] = 1;
                    $params = $insertData ?? $params;

                    // var_dump($params);exit();
                   // 区领导
                    $leader_ids = '';
                    $leader_names = '';
                    if (isset($params['tmp_leader_ids'])) {
                        foreach($params['tmp_leader_ids'] as $key => $value)
                        {
                            $leader_ids .= $value.",";
                            $leader_names .= getSelectText('leader',$value).',';
                        }
                        $leader_ids = substr($leader_ids,0,strlen($leader_ids)-1); 
                        $leader_names = substr($leader_names,0,strlen($leader_names)-1); 
                    }

                    $params['leader_ids'] = $leader_ids;
                    $params['leader_names'] = $leader_names;
                    $params['tmp_leader_ids'] = $leader_ids;
                    $params['tmp_leader_names'] = $leader_names;
                    // pr($params);

                    // 陪同单位
                    $accompany_ids = '';
                    $accompany_name = '';
                    if (isset($params['tmp_accompany_ids'])) {
                        foreach($params['tmp_accompany_ids'] as $key => $v)
                        {
                            $accompany_ids .= $v.",";
                            $row_info = $this->chargedep_model->get($v);
                            $accompany_name .= $row_info->name.',';
                        }
                        $accompany_ids = substr($accompany_ids,0,strlen($accompany_ids)-1); 
                        $accompany_name = substr($accompany_name,0,strlen($accompany_name)-1); 
                    }
                    $params['accompany_ids'] = $accompany_ids;
                    $params['accompany_name'] = $accompany_name;
                    $params['tmp_accompany_ids'] = $accompany_ids;
                    $params['tmp_accompany_name'] = $accompany_name;

                    if(isset($params['tmp_project_status']))    
                    $params['tmp_project_status_name'] = config('app.project_status')[$params['tmp_project_status']];
                }
                else{
                    $params['status'] = -1;


                   // 区领导
                    $leader_ids = '';
                    $leader_names = '';
                    if (isset($params['leader_ids'])) {
                        foreach($params['leader_ids'] as $key => $value)
                        {
                            $leader_ids .= $value.",";
                            $leader_names .= getSelectText('leader',$value).',';
                        }
                        $leader_ids = substr($leader_ids,0,strlen($leader_ids)-1); 
                        $leader_names = substr($leader_names,0,strlen($leader_names)-1); 
                    }

                    $params['leader_ids'] = $leader_ids;
                    $params['leader_names'] = $leader_names;
                    // pr($params);

                    // 陪同单位
                    $accompany_ids = '';
                    $accompany_name = '';
                    if (isset($params['accompany_ids'])) {
                        foreach($params['accompany_ids'] as $key => $v)
                        {
                            $accompany_ids .= $v.",";
                            $row_info = $this->chargedep_model->get($v);
                            $accompany_name .= $row_info->name.',';
                        }
                        $accompany_ids = substr($accompany_ids,0,strlen($accompany_ids)-1); 
                        $accompany_name = substr($accompany_name,0,strlen($accompany_name)-1); 
                    }
                    $params['accompany_ids'] = $accompany_ids;
                    $params['accompany_name'] = $accompany_name;


                    // 责任部门
                    $chargedep_ids = '';
                    $chargedep_names = '';
                    if (isset($params['chargedep_ids'])&&is_array($params['chargedep_ids'])) {
                        foreach($params['chargedep_ids'] as $key => $v)
                        {
                            $chargedep_ids .= $v.",";
                            $row_info = $this->chargedep_model->get($v);
                            $chargedep_names .= $row_info->name.',';
                        }
                        $chargedep_ids = substr($chargedep_ids,0,strlen($chargedep_ids)-1); 
                        $chargedep_names = substr($chargedep_names,0,strlen($chargedep_names)-1); 
                    }
                    $params['chargedep_ids'] = $chargedep_ids;
                    $params['chargedep_names'] = $chargedep_names;
                    // $params['tmp_chargedep_ids'] = $chargedep_ids;
                    // $params['tmp_chargedep_names'] = $chargedep_names;

                    if(isset($params['project_status'])){
                        $params['project_status_name'] = config('app.project_status')[$params['project_status']];
                        if($params['project_time']>0)
                            $status = config('app.project_status')[$params['project_status']]."(".$params['project_time'].")";
                        else
                            $status = config('app.project_status')[$params['project_status']]; 
                        $params['project_status_demo'] = $status.",";
                    }
                }

                

                $params['is_add'] = 1;
                $params['add_memo'] = '新增';
                $params['is_visible'] = 0;

                $params['create_time'] = time();
                $params['update_time'] = time();

                // pr($params);exit();

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                     // pr($params);exit();

                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();

    }
    public function edit($ids = NULL) {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $field = $this->request->post("item_id");
                $data = [];
                $params_field = $this->auth->isSuperAdmin() ? $field :'tmp_'.$field;

                if(!$this->auth->isSuperAdmin()){
                    $data['tmp_'.$field] = $params['value'];
                    $data['tmp_'.$field.'_submit_desc'] = $params['desc_value'];
                    $data['tmp_'.$field.'_status'] = STATUS_SUBMIT;
                    $data['status'] = 1;

                    // 区领导
                    if (isset($data['tmp_leader_ids'])) {
                        $str = '';
                        $str_name = '';
                        foreach($data['tmp_leader_ids'] as $key => $value)
                        {
                            $str .= $value.",";
                            $str_name .= getSelectText('leader',$value).',';
                        }
                        $str = substr($str,0,strlen($str)-1); 
                        $str_name = substr($str_name,0,strlen($str_name)-1);

                        $data['tmp_leader_ids'] = $str;
                        $data['tmp_leader_names'] = $str_name;
                    }

                    // 陪同单位
                    if (isset($data['tmp_accompany_ids'])) {
                        $accompany_ids = '';
                        $accompany_name = '';
                        foreach($data['tmp_accompany_ids'] as $key => $v)
                        {
                            $accompany_ids .= $v.",";
                            $row_info = $this->chargedep_model->get($v);
                            $accompany_name .= $row_info->name.',';
                        }
                        $accompany_ids = substr($accompany_ids,0,strlen($accompany_ids)-1); 
                        $accompany_name = substr($accompany_name,0,strlen($accompany_name)-1);

                        $data['tmp_accompany_ids'] = $accompany_ids;
                        $data['tmp_accompany_name'] = $accompany_name;
                    }
                    
                    // 项目状态
                    if(isset($data['tmp_project_status']))
                        $data['tmp_project_status_name'] = config('app.project_status')[$data['tmp_project_status']];
                    if(isset($data['tmp_project_status'])&&$data['tmp_project_status']>1)
                        $data['tmp_project_time'] = strtotime($this->request->post("project_time"));
                    // pr($this->request->post("project_time"));exit();
                }
                else{
                    $data[$field] = $params['value'];

                    // 管理员
                    // 区领导
                    if (isset($data['leader_ids'])) {
                        $str = '';
                        $str_name = '';
                        foreach($data['leader_ids'] as $key => $value)
                        {
                            $str .= $value.",";
                            $str_name .= getSelectText('leader',$value).',';
                        }
                        $str = substr($str,0,strlen($str)-1); 
                        $str_name = substr($str_name,0,strlen($str_name)-1);
                        $data['leader_ids'] = $str;
                        $data['leader_names'] = $str_name;
                    }

                    // 陪同单位
                    if (isset($data['accompany_ids'])) {
                        $accompany_ids = '';
                        $accompany_name = '';
                        foreach($data['accompany_ids'] as $key => $v)
                        {
                            $accompany_ids .= $v.",";
                            $row_info = $this->chargedep_model->get($v);
                            $accompany_name .= $row_info->name.',';
                        }
                        $accompany_ids = substr($accompany_ids,0,strlen($accompany_ids)-1); 
                        $accompany_name = substr($accompany_name,0,strlen($accompany_name)-1);
                        $data['accompany_ids'] = $accompany_ids;
                        $data['accompany_name'] = $accompany_name;  
                    }
                 
                    // 责任部门
                    if(isset($data['chargedep_ids'])) {
                        $chargedep_ids = '';
                        $chargedep_names = '';
                        foreach($data['chargedep_ids'] as $key => $val)
                        {
                            $chargedep_ids .= $val.",";
                            $row_info = $this->chargedep_model->get($val);
                            $chargedep_names .= $row_info->name.',';
                        }
                        $chargedep_ids = substr($chargedep_ids,0,strlen($chargedep_ids)-1); 
                        $chargedep_names = substr($chargedep_names,0,strlen($chargedep_names)-1); 
                        $data['chargedep_ids'] = $chargedep_ids;
                        $data['chargedep_names'] = $chargedep_names;
                    }

                    // // 项目状态
                    if(isset($data['project_status']))
                        $data['project_status_name'] = config('app.project_status')[$data['project_status']];
                    if(isset($data['project_status'])&&$data['project_status']>1){
                        $data['project_time'] = strtotime($this->request->post("project_time"));
                        if($data['project_time']>0)
                            $status = config('app.project_status')[$data['project_status']]."(".date('Y-m-d',$data['project_time']).")";
                        else
                            $status = config('app.project_status')[$data['project_status']];                
                        $data['project_status_demo'] = $row['project_status_demo'].$status.",";
                    }


                }

                $logData[] = [
                    'approach_id' => $row -> id,
                    'admin_id'  => $this -> auth -> id,
                    'admin_nickname' => $this->auth->nickname,
                    'field' => $field,
                    'field_name' =>$this -> fieldNames[$field],
                    'ori_value' => $row -> $params_field,
                    'new_value' => is_array($params['value']) ? implode(',',$params['value']) : $params['value'],
                    'status' => STATUS_SUBMIT,
                    'info'  => $this -> auth -> isSuperAdmin() ? '管理员修改' : '申请提交',
                    'desc' => $params['desc_value'],
                    'create_time' => time(),
                    'update_time'   => time()
                ];
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($data);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if($logData){
                        Db::name('approachlog') -> insertAll($logData);
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig('ids',$ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    public function initedit($ids) {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $data = $this->request->post("row/a");

            // pr($data);exit('222222');
            if ($data) {
                $data = $this->preExcludeFields($data);

                $updateData = [];

                foreach ($data as $k => $v) {

                    if(isset($row -> $k) && $row -> $k != (is_array($data[$k]) ? implode(',',$data[$k]) : $data[$k])){
                        if(is_int($row -> $k) && (substr($k,-5) == '_time') && date("Y-m-d",$row -> $k) == $data[$k]) continue;
                        $key = $this -> auth -> isSuperAdmin() ? $k : 'tmp_'.$k;
                        $updateData[$key] = $data[$k];
                        $updateData[$key.'_status'] = STATUS_SUBMIT;
                        if(isset($data[$k.'_submit_desc']))
                            $updateData[$key.'_submit_desc'] = $data[$k.'_submit_desc'];
                        $logData[] = [
                            'approach_id' => $row -> id,
                            'admin_id'  => $this -> auth -> id,
                            'admin_nickname' => $this->auth->nickname,
                            'field' => $k,
                            'field_name' => $this -> tmpFieldNames[$k] ?? ($this -> fieldNames[$k] ?? ''),
                            'ori_value' => $row -> $k,
                            'new_value' => is_array($data[$k]) ? implode(',',$data[$k]) : $data[$k],
                            'status' =>  100,
                            'info'  => $this -> auth -> isSuperAdmin() ? '管理员修改' : '申请提交',
                            'desc' => isset($data[$k.'_submit_desc'])?$data[$k.'_submit_desc']:'',
                            'create_time' => time(),
                            'update_time'   => time()
                        ];
                    }
                }
                if($updateData)
                    $updateData['status'] = $this -> auth -> isSuperAdmin() ? 0 : 1;
                // pr($logData);
                // pr($updateData);
                // if($logData){
                //     Db::name('approachlog') -> insertAll($logData);
                // }
                // if($updateData){
                //     // if(!$this -> auth -> isSuperAdmin()){
                //     //     $updateData['status'] = 100;
                //     // }

                //     $ret = $row -> save($updateData);
                // }
                if (!$this -> auth -> isSuperAdmin()) {
                    // 项目状态
                    if(isset($updateData['tmp_project_status']))
                        $updateData['tmp_project_status_name'] = config('app.project_status')[$updateData['tmp_project_status']];
                    if(isset($updateData['tmp_project_status'])&&$updateData['tmp_project_status']>1)
                        $updateData['tmp_project_time'] = strtotime($this->request->post("project_time")); 
                }else{
                    // 项目状态
                    if(isset($updateData['project_status']))
                        $updateData['project_status_name'] = config('app.project_status')[$updateData['project_status']];
                    if(isset($updateData['project_status'])&&$updateData['project_status']>1){
                        $updateData['project_time'] = strtotime($this->request->post("project_time"));
                        if($updateData['project_time']>0)
                            $status = config('app.project_status')[$updateData['project_status']]."(".date('Y-m-d',$updateData['project_time']).")";
                        else
                            $status = config('app.project_status')[$updateData['project_status']];                
                        $data['project_status_demo'] = $row['project_status_demo'].$status.",";
                    }                 
                }

                if(!$this -> auth -> isSuperAdmin())
                {
                   // 区领导
                    if (isset($updateData['tmp_leader_ids'])) {
                        $leader_ids = '';
                        $leader_names = '';
                        foreach($updateData['tmp_leader_ids'] as $key => $value)
                        {
                            $leader_ids .= $value.",";
                            $leader_names .= getSelectText('leader',$value).',';
                        }
                        $leader_ids = substr($leader_ids,0,strlen($leader_ids)-1); 
                        $leader_names = substr($leader_names,0,strlen($leader_names)-1); 
                        // $updateData['leader_ids'] = $leader_ids;
                        // $updateData['leader_names'] = $leader_names;
                        $updateData['tmp_leader_ids'] = $leader_ids;
                        $updateData['tmp_leader_names'] = $leader_names;
                    }


                    // pr($params);
                    // 陪同单位
                    if (isset($updateData['tmp_accompany_ids'])) {  
                        $accompany_ids = '';
                        $accompany_name = '';
                        foreach($updateData['tmp_accompany_ids'] as $key => $v)
                        {
                            $accompany_ids .= $v.",";
                            $row_info = $this->chargedep_model->get($v);
                            $accompany_name .= $row_info->name.',';
                        }
                        $accompany_ids = substr($accompany_ids,0,strlen($accompany_ids)-1); 
                        $accompany_name = substr($accompany_name,0,strlen($accompany_name)-1); 
                        // $updateData['accompany_ids'] = $accompany_ids;
                        // $updateData['accompany_name'] = $accompany_name;
                        $updateData['tmp_accompany_ids'] = $accompany_ids;
                        $updateData['tmp_accompany_name'] = $accompany_name;

                    }                    
                }else{
                                       // 区领导
                    if (isset($updateData['leader_ids'])) {
                        $leader_ids = '';
                        $leader_names = '';
                        foreach($updateData['leader_ids'] as $key => $value)
                        {
                            $leader_ids .= $value.",";
                            $leader_names .= getSelectText('leader',$value).',';
                        }
                        $leader_ids = substr($leader_ids,0,strlen($leader_ids)-1); 
                        $leader_names = substr($leader_names,0,strlen($leader_names)-1); 
                        $updateData['leader_ids'] = $leader_ids;
                        $updateData['leader_names'] = $leader_names;
                    }


                    // pr($params);
                    // 陪同单位
                    if (isset($updateData['accompany_ids'])) {  
                        $accompany_ids = '';
                        $accompany_name = '';
                        foreach($updateData['accompany_ids'] as $key => $v)
                        {
                            $accompany_ids .= $v.",";
                            $row_info = $this->chargedep_model->get($v);
                            $accompany_name .= $row_info->name.',';
                        }
                        $accompany_ids = substr($accompany_ids,0,strlen($accompany_ids)-1); 
                        $accompany_name = substr($accompany_name,0,strlen($accompany_name)-1); 
                        $updateData['accompany_ids'] = $accompany_ids;
                        $updateData['accompany_name'] = $accompany_name;

                    }
                }

                // pr($updateData);
                // exit();
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($updateData);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if(isset($logData)){
                        Db::name('approachlog') -> insertAll($logData);
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function checkedit($ids){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $data = [];
            foreach ($this -> Fields as $key => $value) {
                // var_dump($value);
                if($row['tmp_'.$value.'_status'] == STATUS_SUBMIT)
                {
                    $logData[] = [
                            'approach_id' => $row -> id,
                            'admin_id'  => $this -> auth -> id,
                            'admin_nickname' => $this->auth->nickname,
                            'field' => $value,
                            'field_name' => $this -> tmpFieldNames[$value] ?? ($this -> fieldNames[$value] ?? ''),
                            'ori_value' => $row -> $value,
                            'new_value' => $row['tmp_'.$value],
                            'status' => $this -> auth -> isSuperAdmin() ? 300 : 100,
                            'info'  => '审核',
                            'create_time' => time(),
                            'update_time'   => time()
                    ];
                    $data[$value] = $row['tmp_'.$value];
                    $data['tmp_'.$value] = null;
                    $data['tmp_'.$value.'_submit_desc'] = null;
                    $data['tmp_'.$value.'_status'] = STATUS_PASS;
                }
            }
            $data['status'] = 0;
            $data['is_visible'] = 1;

            // pr($data);
            // exit();

            // 区领导
            if (isset($data['leader_ids'])) {
                $leader_names = '';
                foreach(explode(',', $data['leader_ids']) as $key => $value)
                {
                    $leader_names .= getSelectText('leader',$value).',';
                } 
                $leader_names = substr($leader_names,0,strlen($leader_names)-1); 
                $data['leader_ids'] = $data['leader_ids'];
                $data['leader_names'] = $leader_names;
                $data['tmp_leader_names'] = null;
            }
            // 陪同单位
            if (isset($data['accompany_ids'])) {  
                $accompany_name = '';
                foreach(explode(',', $data['accompany_ids']) as $key => $v)
                {
                    $row_info = $this->chargedep_model->get($v);
                    $accompany_name .= $row_info->name.',';
                } 
                $accompany_name = substr($accompany_name,0,strlen($accompany_name)-1); 
                $data['accompany_ids'] = $data['accompany_ids'];
                $data['accompany_name'] = $accompany_name;
                $data['tmp_accompany_name'] = null;
            }

            // 项目状态
            if (isset($data['project_status']))
            {  
                if(isset($row['tmp_project_time'])){
                    $data['project_time'] = $row['tmp_project_time']; 
                    $data['tmp_project_time'] = null;
                } 
                $data['project_status_name'] = $row['tmp_project_status_name']; 
                if($data['project_time']>0)
                    $status = $row['tmp_project_status_name']."(".date('Y-m-d',$data['project_time']).")";
                else
                    $status = $row['tmp_project_status_name'];                
                $data['project_status_demo'] = $row['project_status_demo'].$status.",";

                $data['tmp_project_status_name'] = null;

            }           
            $result = false;
            $result = $row->allowField(true)->save($data);
            if ($result !== false) {
                if($logData){
                    Db::name('approachlog') -> insertAll($logData);
                }
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }

        }
        $this->assignconfig('ids',$ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function detail($ids = null){
        if(!$ids){
            $this -> error('请刷新重试');
        }

        $row = $this -> model -> find($ids);
        $row['project_status_demo'] = str_replace(",","<br/>",$row['project_status_demo']);
        // pr($row['project_status_demo']);

        $this -> assign('is_norecords',$this -> request -> param('is_norecords',0));
        $this -> assign('records',\app\admin\model\Approach::all(['name' => $row -> name]));

        $this -> assign('row',$row);
        return $this -> fetch();
    }

    public function rejectmemo($ids = null){

        $row = $this->model->where('id',$ids)->where($this->whereExtend)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }


        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['reject_memo_status'] = 1;
            $result = false;
            $result = $row->allowField(true)->save($params);
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->assign('row',$row);
        return $this->view->fetch();
    }

}
